// pages/luoAn/deviceIndex.js
const App = getApp()
const appkey = "MLCBZ-QUCYO-MAHWW-S7ZTA-G6IR2-AZFM5";
const {
  QQMapWX,
  LuoAnHttp,
  bgMusic
} = App.globalData;
var qqmapsdk = new QQMapWX({
  key: appkey
});
const ScanTypeMapper = {
  none: -1, //无任何提示的时候
  recognizeAndNotAdd: 0, // 识别成功 并且还么有绑定
  hasBeenBinded: 3, // 识别成功 但是已经被人绑定了
  canNotRecognize: 1, // 不能正确识别
}
const musicSrc = "http://minganzhineng.oss-cn-beijing.aliyuncs.com/baojing/alarmsound.mp3"

const CheckAlarmFormat = function (item) {
  if (item.manual == 'Y') { // 手动解除；不需要警告；返回false
    return false
  } else {
    if (item.smoketype == "Y") {
      return false
    } else {
      return true
    }
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataSource: [],
    userId: wx.getStorageSync('userId'),
    adVertisementList: [{
      addressUrl: 'http://minganzhineng.oss-cn-beijing.aliyuncs.com/mingan/2c55555b7d4c466082ddb294b9a187da.png'
    }],
    /**
     * 扫码部分
     */
    type: ScanTypeMapper.none, // 默认什么也没有
    devieSN: '',
    currentDevice: {}, // 扫描到的设备信息
    locationParma: {}, // 位置参数

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    this.loadBanner();
    this.loadDeviceFresh()
  },
  loadDeviceFresh: function (e) {
    const userId = wx.getStorageSync('userId');
    if (userId) {
      this.setData({
        userId: userId
      })
      this.loadDeviceList({
        pagesize: 10,
        pagecurrent: 1
      })
    }
  },
  loadBanner: async function (e) {
    const res = await LuoAnHttp.asyncGetBannerList({});
    if (res && res.data.length>0) {
      this.setData({
        adVertisementList: res.data.filter(v => v.statetype == '1')
      })
    }
  },
  jumpLogin: function (e) {
    wx.navigateTo({
      url: '/pages/luoAn/common/loginIndex',
    })
  },
  bindgetphonenumber: async function (e) {
    console.log(e);

    const detail = e.detail;
    if (detail) {
      const code1 = await LuoAnHttp.asynWXLogin({});
      const {
        encryptedData,
        iv
      } = detail
      const res = await LuoAnHttp.asyncCommonDecode({
        encryptedData,
        iv,
        code: code1
      });

      if (res && res.data) {
        const mobile = res.data.phoneNumber
        const code2 = await LuoAnHttp.asynWXLogin({});
        const openIdData = await LuoAnHttp.asyncCommonGetOpenId({
          code: code2
        })
        if (openIdData && openIdData.data) {
          const loginRes = await LuoAnHttp.asyncLogin({
            mobile,
            openid: openIdData.data.openid
          });
          if (loginRes && loginRes.code == 200) {
            const userIdData = await LuoAnHttp.asyncGetUserId({
              phone: mobile
            })

            if (userIdData.data) {
              wx.setStorageSync('userId', userIdData.data.userid)
              this.setData({
                userId: userIdData.data.userid
              })
              this.loadDeviceList({
                pagesize: 10,
                pagecurrent: 1
              })
            }
          }
        }
      }
    }
  },
  loadDeviceList: async function (param = {
    pagesize: 10,
    pagecurrent: 1
  }) {
    const deviceList = await LuoAnHttp.asyncGetDeviceList(param)
    if (deviceList && deviceList.data) {
      const list = param.pagecurrent == 1 ? [].concat(deviceList.data.records) : this.data.dataSource.concat(deviceList.data.records);
      const alarming = list.filter(v => CheckAlarmFormat(v));
      if (alarming.length > 0) {
        this.listenerButtonPlay()
      } else {
        this.listenerButtonStop()
      }

      this.setData({
        dataSource: list,
        pagecurrent: param.pagecurrent
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadDeviceFresh()
  },
  sanQRBar: function (e) {
    if (this.data.userId == null || this.data.userId.length == 0) {
      wx.navigateTo({
        url: '/pages/luoAn/common/loginIndex',
      })
    } else {
      this.openScanCode()
    }

  },
  listenerButtonPlay: function () {
    console.log("LAOMI 开始播放")
    if(this.audioContext==null){
      this.audioContext = wx.createInnerAudioContext(); 
    }else{
      this.audioContext.stop()
    }
    this.audioContext.src = musicSrc;
    this.audioContext.loop = true;
    this.audioContext.play();








  },
  //停止播放
  listenerButtonStop: function () {
    console.log('LAOMI 停止播放');
    if(this.audioContext){
      this.audioContext.stop();
      this.audioContext.destroy();
      this.audioContext = null       
    }
    

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.loadDeviceList({
      pagesize: 10,
      pagecurrent: 1
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.loadDeviceList({
      pagesize: 10,
      pagecurrent: 1 + this.data.pagecurrent
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  addressOnClick: function (e) {
    wx.navigateTo({
      url: './DeviceAddressDetail',
      events: {
        callback: f => this.onLoad(),
      },
      success: ({
        eventChannel
      }) => {

        eventChannel.emit('param', e.detail)
      }
    })
  },

  /**
   * 扫码部分
   */
  location: function (e) {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        altitude: false,
        success: e => resolve({
          longitude: e.longitude,
          latitude: e.latitude
        }),
        fail: f => resolve(null)
      })
    })
  },
  reverGeo: function (param) {
    return new Promise((relove, reject) => {
      qqmapsdk.reverseGeocoder({
        // coord_type:'gcj02',
        location: param,
        success: s => {
          relove && relove(s.result)
        },
        fail: f => {
          reject && reject(null)
        }
      })
    })
  },
  openScanCode: function (e) {
    wx.hideTabBar({
      animation: false,
    })
    wx.scanCode({
      onlyFromCamera: false,
      success: s => this.scanSuccess(s),
      fail: f => this.scanFailed(f)
    })
  },
  cancelScan: function (e) {
    this.setData({
      type: ScanTypeMapper.none,
      snInput: ''
    })
    wx.showTabBar({
      animation: false,
    })
  },
  // 重新扫描
  scanAgain: function (e) {

    this.openScanCode()
    this.setData({
      type: ScanTypeMapper.none
    })

  },
  bindDevice: async function (e) {
    const location = await this.location()

    if (location == null) {
      wx.showModal({
        title: '提示',
        content: '定位权限未开启,请打开',
        success: res => {
          if (res.confirm) {
            wx.openSetting({
              withSubscriptions: true,
            })
          } else if (res.cancel) {
            wx.openSetting({
              withSubscriptions: true,
            })
          }
        },
      })
      return
    }
    const res = await this.reverGeo(location)
    if (res) {

      const param = {
        longitudeandlatitude: `${location.longitude},${location.latitude}`,
        deviceposition: res.address,
        ...this.data.currentDevice,
      }
      const res2 = await LuoAnHttp.asyncBindAction(param)
      if (res2) {
        this.cancelScan()
        this.loadDeviceList()
      }
    }

  },
  scanSuccess: async function (success) {

    const {
      result
    } = success;
    const arr = result.split(',');
    if (arr.length === 3) {
      const param = {
        hardwarecode: arr[0],
        iotcard: arr[1],
        devicetype: arr[2]
      };
      const queryResult = await LuoAnHttp.asyncBindStatusQuery(param);
      switch (parseInt(queryResult.data)) {
        case 0:
          this.setData({
            type: ScanTypeMapper.recognizeAndNotAdd,
            currentDevice: param
          })
          break;
        case 1:
          this.setData({
            type: ScanTypeMapper.canNotRecognize,
            currentDevice: param
          })
          break;
        case 2:
          this.setData({
            type: ScanTypeMapper.canNotRecognize,
            currentDevice: param
          })
          break;
        case 3:
          this.setData({
            type: ScanTypeMapper.hasBeenBinded,
          })
          break;
      }
    } else { //不是合适的二维码
      this.setData({
        type: ScanTypeMapper.canNotRecognize
      })
    }
    console.log(success)
  },
  scanFailed: function (fail) {
    console.log(fail)
    if (fail.errMsg && fail.errMsg.indexOf('cancel') != -1) {
      wx.showTabBar({
        animation: false,
      })
    } else {
      this.setData({
        type: ScanTypeMapper.canNotRecognize,
      })
    }
  },
  snInput: function (e) {
    const detail = e.detail;
    console.log(e);
    this.setData({
      devieSN: detail.value
    })
  },
  queryAndBind: async function (e) {
    if (this.data.devieSN.length !== 12) {
      wx.showToast({
        title: '请输入12位id',
        icon: 'none'
      })
      return
    }
    const param = {
      hardwarecode: this.data.devieSN
    };
    const queryResult = await LuoAnHttp.asyncBindStatusQuery(param);
    switch (parseInt(queryResult.data)) {
      case 0:
        this.setData({
          type: ScanTypeMapper.recognizeAndNotAdd,
          currentDevice: param
        })
        break;
      case 1:
        this.setData({
          type: ScanTypeMapper.canNotRecognize,
          currentDevice: param
        })
        break;
      case 2:
        this.setData({
          type: ScanTypeMapper.canNotRecognize,
          currentDevice: param
        })
        break;
      case 3:
        this.setData({
          type: ScanTypeMapper.hasBeenBinded,
          currentDevice: param
        })
        break;
    }

  }
})